package com.haoxiaozhang.hxz_app.net;

import android.util.Log;

import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;

public abstract class CommonCallback<T> extends StringCallback {

    Type mType;

    public CommonCallback(){
        Class<? extends CommonCallback> clazz = getClass();
        Type genericSuperclass = clazz.getGenericSuperclass();
        if(genericSuperclass instanceof Class){
            throw new RuntimeException("没有传入泛型参数");
        }

        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        mType = parameterizedType.getActualTypeArguments()[0];
    }



    public abstract void onError(Exception e);
    public abstract void onSuccess(T response);

    @Override
    public void onError(Call call, Exception e) {
        onError(e);
    }

    @Override
    public void onResponse(String response) {
        try {

            JSONObject resp = new JSONObject(response);
            boolean isSuccess = resp.getBoolean("success");


            if(isSuccess){

                String data = resp.getString("result");
                Gson gson = new Gson();
                onSuccess((T) gson.fromJson(data,mType));

            }else{

                //获取错误信息
                JSONObject o = resp.getJSONObject("error");
                String errMessage = o.getString("message");

                onError(new RuntimeException(errMessage));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


}
